package model

import (
	"bytes"
	"fmt"
	"gorm.io/gorm"
)

type (
	UserGroupModel struct {
		db *gorm.DB
	}
	// UserGroup  用户—组
	UserGroup struct {
		ID      int64     `gorm:"primarykey" json:"id"`
		Uid     int64     `gorm:"index" gorm:"comment: 用户ID" json:"uid"`
		GroupId int64     `gorm:"comment: 权限组" json:"group_id"`
		Group   AuthGroup `gorm:"foreignKey:GroupId"`
		RoleId  int64     `gorm:"comment: 角色" json:"role_id"`
		Role    AuthRole  `gorm:"foreignKey:RoleId"`
	}
)

func NewUserGroupMode(gormDb *gorm.DB) *UserGroupModel {
	return &UserGroupModel{
		db: gormDb,
	}
}

func (m *UserGroupModel) FindUserRoleByUid(uid int64) ([]UserGroup, error) {
	var userGroup []UserGroup
	err := m.db.Preload("Group").Preload("Role").Where("uid = ?", uid).Find(&userGroup).Error
	if err != nil {
		return userGroup, err
	}
	return userGroup, nil
}

func (m *UserGroupModel) AddGroupRole(userGroup *UserGroup) error {
	return m.db.Create(userGroup).Error
}

func (m *UserGroupModel) UpdateByUid(uid int64, userRole UserRole) (int64, error) {
	resp := m.db.Where("uid = ?", uid).Updates(userRole)
	return resp.RowsAffected, resp.Error
}

func (m *UserGroupModel) DelGroupRole(uid int64, groupId int64) (int64, error) {
	session := m.db.Where("uid = ?", uid)
	if groupId != 0 {
		session.Where("group_id = ?", groupId)
	}
	resp := session.Delete(&UserGroup{})
	return resp.RowsAffected, resp.Error
}

// BatchSave 批量插入数据.
func (m *UserGroupModel) BatchSave(emps []UserGroup) error {
	var buffer bytes.Buffer
	sql := "insert into user_groups (uid, group_id, role_id) values"
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	for i, e := range emps {
		if i == len(emps)-1 {
			buffer.WriteString(fmt.Sprintf("('%d','%d','%d');", e.Uid, e.GroupId, e.RoleId))
		} else {
			buffer.WriteString(fmt.Sprintf("('%d','%d','%d'),", e.Uid, e.GroupId, e.RoleId))
		}
	}
	return m.db.Exec(buffer.String()).Error
}

func (m *UserGroupModel) GetUserGroupByGroupIdAndUid(uid int64, groupId int64) (UserGroup, error) {
	var userGroup UserGroup
	tx := m.db.Where("uid = ?", uid).Where("group_id = ?", groupId).First(&userGroup)
	return userGroup, tx.Error
}

func (m *UserGroupModel) GetUserGroupByIds(ids []int64) ([]UserGroup, error) {
	var list []UserGroup
	tx := m.db.Where("group_id in ?", ids).First(&list)
	return append([]UserGroup{}, list...), tx.Error
}
